// async_paging_differ.cc - 异步分页差异计算器实现文件
#include "async_paging_differ.h"
#include "diff_util.h"
#include "paging_controller.h"
#include <hilog/log.h>
#include <sstream>
#include <chrono>
#include <thread>
#include <algorithm>

// =========== HarmonyOS HiLog 配置 ===========
// 定义日志域和标签
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200  // 业务领域标识，范围 0x0 到 0xFFFFF
#define LOG_TAG "AsyncPagingDiffer"

// =========== 日志宏定义 ===========
// 使用 HarmonyOS 提供的原生日志宏
// 可通过 DISABLE_LOGGING 宏来控制是否启用日志
#ifdef DISABLE_LOGGING
    // 禁用所有日志输出
    #define LOGI(...) ((void)0)
    #define LOGW(...) ((void)0)
    #define LOGE(...) ((void)0)
    #define LOGD(...) ((void)0)
    #define LOGF(...) ((void)0)
#else
    // 启用日志输出 - 使用 HarmonyOS 原生宏
    // OH_LOG_XXX 宏会自动处理 LogType 和 LogLevel 枚举
    #define LOGI(...) OH_LOG_INFO(LOG_APP, __VA_ARGS__)
    #define LOGW(...) OH_LOG_WARN(LOG_APP, __VA_ARGS__)
    #define LOGE(...) OH_LOG_ERROR(LOG_APP, __VA_ARGS__)
    #define LOGD(...) OH_LOG_DEBUG(LOG_APP, __VA_ARGS__)
    #define LOGF(...) OH_LOG_FATAL(LOG_APP, __VA_ARGS__)
#endif

// ============ ListUpdateCallback 默认实现 ============

// 默认的空回调实现
class DefaultListUpdateCallback : public ListUpdateCallback {
public:
    void onInserted(int position, int count) override {
        LOGI("Default onInserted: position=%{public}d, count=%{public}d", position, count);
    }
    
    void onRemoved(int position, int count) override {
        LOGI("Default onRemoved: position=%{public}d, count=%{public}d", position, count);
    }
    
    void onMoved(int fromPosition, int toPosition) override {
        LOGI("Default onMoved: from=%{public}d, to=%{public}d", fromPosition, toPosition);
    }
    
    void onChanged(int position, int count, void* payload) override {
        LOGI("Default onChanged: position=%{public}d, count=%{public}d, payload=%{public}p", position, count, payload);
    }
};

// ============ PagingItemAdapter - 适配器类 ============

// 将 PagingItem 回调适配为 DiffUtil 期望的类型
template<typename T>
class PagingItemAdapter : public DiffUtil<std::shared_ptr<PagingItem<T>>>::ItemCallback {
private:
    // 内部存储 PagingItem 的引用，用于比较
    mutable std::vector<std::shared_ptr<PagingItem<T>>> oldItems_;
    mutable std::vector<std::shared_ptr<PagingItem<T>>> newItems_;
    
public:
    // 设置要比较的项目列表
    void setItems(const std::vector<std::shared_ptr<PagingItem<T>>>& oldItems,
                  const std::vector<std::shared_ptr<PagingItem<T>>>& newItems) const {
        oldItems_ = oldItems;
        newItems_ = newItems;
    }
    
    bool areItemsTheSame(const std::shared_ptr<PagingItem<T>>& oldItem, 
                        const std::shared_ptr<PagingItem<T>>& newItem) const override {
        if (!oldItem || !newItem) return false;
        return oldItem->id == newItem->id;
    }
    
    bool areContentsTheSame(const std::shared_ptr<PagingItem<T>>& oldItem, 
                           const std::shared_ptr<PagingItem<T>>& newItem) const override {
        if (!oldItem || !newItem) return false;
        return oldItem->data == newItem->data;
    }
    
    void* getChangePayload(const std::shared_ptr<PagingItem<T>>& oldItem, 
                          const std::shared_ptr<PagingItem<T>>& newItem) const override {
        return nullptr;
    }
};

// ============ AsyncPagingDataDiffer 特定方法实现 ============

// 修复构造函数实现
template<typename T>
AsyncPagingDataDiffer<T>::AsyncPagingDataDiffer(
    std::unique_ptr<typename DiffUtil<std::shared_ptr<PagingItem<T>>>::ItemCallback> diffCallback,
    ListUpdateCallback* updateCallback)
    : diffCallback_(std::move(diffCallback)),
      updateCallback_(updateCallback),
      mainThreadId_(std::this_thread::get_id()) {
    
    LOGI("AsyncPagingDataDiffer constructor called");
    startWorkerThread();
}

// 修复析构函数
template<typename T>
AsyncPagingDataDiffer<T>::~AsyncPagingDataDiffer() {
    LOGI("AsyncPagingDataDiffer destructor called");
    shutdown();
}

// ============ 显式模板实例化 ============

// 为常用类型提供显式实例化，避免链接错误
template class AsyncPagingDataDiffer<std::string>;
template class AsyncPagingDataDiffer<int>;
template class AsyncPagingDataDiffer<double>;

// ItemSnapshotList 显式实例化
template class ItemSnapshotList<std::string>;
template class ItemSnapshotList<int>;
template class ItemSnapshotList<double>;

// PagingItemAdapter 显式实例化
template class PagingItemAdapter<std::string>;
template class PagingItemAdapter<int>;
template class PagingItemAdapter<double>;

// ============ 辅助函数实现 ============

namespace PagingDifferUtils {
    
    // 创建默认的加载状态
    CombinedLoadStates createDefaultLoadStates() {
        CombinedLoadStates states;
        states.refresh.isLoading = false;
        states.refresh.isError = false;
        states.prepend.isLoading = false;
        states.prepend.isError = false;
        states.append.isLoading = false;
        states.append.isError = false;
        LOGD("Created default load states");
        return states;
    }
    
    // 创建刷新中的加载状态
    CombinedLoadStates createRefreshingLoadStates() {
        CombinedLoadStates states = createDefaultLoadStates();
        states.refresh.isLoading = true;
        LOGD("Created refreshing load states");
        return states;
    }
    
    // 创建加载中的状态（追加）
    CombinedLoadStates createAppendingLoadStates() {
        CombinedLoadStates states = createDefaultLoadStates();
        states.append.isLoading = true;
        LOGD("Created appending load states");
        return states;
    }
    
    // 创建加载中的状态（前置）
    CombinedLoadStates createPrependingLoadStates() {
        CombinedLoadStates states = createDefaultLoadStates();
        states.prepend.isLoading = true;
        LOGD("Created prepending load states");
        return states;
    }
    
    // 创建错误状态
    CombinedLoadStates createErrorLoadStates(const std::string& errorMessage, bool isRefresh) {
        CombinedLoadStates states = createDefaultLoadStates();
        if (isRefresh) {
            states.refresh.isError = true;
            states.refresh.errorMessage = errorMessage;
            LOGE("Created error load states for refresh: %{public}s", errorMessage.c_str());
        } else {
            states.append.isError = true;
            states.append.errorMessage = errorMessage;
            LOGE("Created error load states for append: %{public}s", errorMessage.c_str());
        }
        return states;
    }
    
    // 检查是否有任何加载正在进行
    bool isAnyLoading(const CombinedLoadStates& states) {
        bool loading = states.refresh.isLoading || 
                      states.prepend.isLoading || 
                      states.append.isLoading;
        LOGD("Is any loading: %{public}s", loading ? "true" : "false");
        return loading;
    }
    
    // 检查是否有任何错误
    bool hasAnyError(const CombinedLoadStates& states) {
        bool hasError = states.refresh.isError || 
                       states.prepend.isError || 
                       states.append.isError;
        if (hasError) {
            LOGW("Has error in load states");
        }
        return hasError;
    }
    
    // 获取第一个错误消息
    std::string getFirstErrorMessage(const CombinedLoadStates& states) {
        if (states.refresh.isError && !states.refresh.errorMessage.empty()) {
            return states.refresh.errorMessage;
        }
        if (states.prepend.isError && !states.prepend.errorMessage.empty()) {
            return states.prepend.errorMessage;
        }
        if (states.append.isError && !states.append.errorMessage.empty()) {
            return states.append.errorMessage;
        }
        return "";
    }
    
    // 日志输出加载状态
    void logLoadStates(const CombinedLoadStates& states) {
        LOGI("LoadStates: refresh(loading=%{public}d, error=%{public}d), prepend(loading=%{public}d, error=%{public}d), append(loading=%{public}d, error=%{public}d)",
            states.refresh.isLoading, states.refresh.isError,
            states.prepend.isLoading, states.prepend.isError,
            states.append.isLoading, states.append.isError);
        
        if (hasAnyError(states)) {
            std::string errorMsg = getFirstErrorMessage(states);
            if (!errorMsg.empty()) {
                LOGE("Error message: %{public}s", errorMsg.c_str());
            }
        }
    }
}

// ============ 全局辅助函数 ============

// 创建默认的ListUpdateCallback
std::unique_ptr<ListUpdateCallback> createDefaultListUpdateCallback() {
    LOGD("Creating default ListUpdateCallback");
    return std::make_unique<DefaultListUpdateCallback>();
}

// 验证分页数据的有效性
template<typename T>
bool validatePagingData(const PagingData<T>& data) {
    if (data.items.empty()) {
        LOGW("PagingData contains no items");
        return true; // 空数据也是有效的
    }
    
    // 检查是否有null项
    for (const auto& item : data.items) {
        if (!item) {
            LOGE("PagingData contains null item");
            return false;
        }
    }
    
    LOGD("PagingData validated: %{public}zu items", data.items.size());
    return true;
}

// 显式实例化验证函数
template bool validatePagingData<std::string>(const PagingData<std::string>&);
template bool validatePagingData<int>(const PagingData<int>&);
template bool validatePagingData<double>(const PagingData<double>&);

// ============ 性能监控 ============

namespace PagingPerformance {
    
    class DiffPerformanceMonitor {
    private:
        std::chrono::steady_clock::time_point startTime_;
        std::string operationName_;
        
    public:
        DiffPerformanceMonitor(const std::string& operation) 
            : operationName_(operation),
              startTime_(std::chrono::steady_clock::now()) {
            LOGI("Starting %{public}s", operationName_.c_str());
        }
        
        ~DiffPerformanceMonitor() {
            auto endTime = std::chrono::steady_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
                endTime - startTime_).count();
            LOGI("Completed %{public}s in %{public}lld ms", operationName_.c_str(), duration);
        }
    };
    
    // 监控diff计算性能
    void monitorDiffCalculation(size_t oldSize, size_t newSize) {
        LOGI("Calculating diff: old size=%{public}zu, new size=%{public}zu", oldSize, newSize);
        
        if (oldSize > 1000 || newSize > 1000) {
            LOGW("Large dataset detected, diff calculation may take time");
        }
    }
    
    // 监控内存使用
    void monitorMemoryUsage(size_t itemCount) {
        size_t estimatedMemory = itemCount * sizeof(void*) * 2; // 粗略估计
        if (estimatedMemory > 10 * 1024 * 1024) { // 10MB
            LOGW("High memory usage detected: ~%{public}zu MB", estimatedMemory / (1024 * 1024));
        }
    }
}

// ============ 线程工具 ============

namespace ThreadingUtils {
    
    // 获取当前线程ID的字符串表示
    std::string getCurrentThreadId() {
        std::ostringstream oss;
        oss << std::this_thread::get_id();
        return oss.str();
    }
    
    // 检查是否在主线程
    bool isMainThread(const std::thread::id& mainThreadId) {
        bool isMain = std::this_thread::get_id() == mainThreadId;
        LOGD("Is main thread: %{public}s", isMain ? "true" : "false");
        return isMain;
    }
    
    // 设置线程名称（如果平台支持）
    void setThreadName(const std::string& name) {
        #ifdef __linux__
        pthread_setname_np(pthread_self(), name.c_str());
        #endif
        LOGI("Thread named: %{public}s", name.c_str());
    }
    
    // 安全的线程join
    void safeJoinThread(std::thread& thread, const std::string& threadName) {
        if (thread.joinable()) {
            LOGI("Waiting for %{public}s to finish...", threadName.c_str());
            thread.join();
            LOGI("%{public}s finished", threadName.c_str());
        }
    }
}

// ============ 调试工具 ============

namespace DebugUtils {
    
    // 打印项目快照信息
    template<typename T>
    void printSnapshotInfo(const ItemSnapshotList<T>& snapshot) {
        LOGI("Snapshot info: size=%{public}zu, generation=%{public}d", 
             snapshot.size(), snapshot.generation());
        
        if (snapshot.size() > 0) {
            auto firstItem = snapshot.get(0);
            auto lastItem = snapshot.get(snapshot.size() - 1);
            if (firstItem) {
                LOGD("First item ID: %{public}s", firstItem->id.c_str());
            }
            if (lastItem) {
                LOGD("Last item ID: %{public}s", lastItem->id.c_str());
            }
        }
    }
    
    // 打印差异结果统计
    template<typename T>
    void printDiffStats(const typename DiffUtil<std::shared_ptr<PagingItem<T>>>::DiffResult& result) {
        int insertCount = 0, removeCount = 0, moveCount = 0, changeCount = 0;
        
        for (const auto& op : result.getOperations()) {
            switch (op.type) {
                case DiffUtil<std::shared_ptr<PagingItem<T>>>::OpType::INSERT:
                    insertCount += op.count;
                    break;
                case DiffUtil<std::shared_ptr<PagingItem<T>>>::OpType::REMOVE:
                    removeCount += op.count;
                    break;
                case DiffUtil<std::shared_ptr<PagingItem<T>>>::OpType::MOVE:
                    moveCount++;
                    break;
                case DiffUtil<std::shared_ptr<PagingItem<T>>>::OpType::CHANGE:
                    changeCount += op.count;
                    break;
                default:
                    break;
            }
        }
        
        LOGI("Diff stats: %{public}d inserted, %{public}d removed, %{public}d moved, %{public}d changed",
             insertCount, removeCount, moveCount, changeCount);
    }
    
    // 显式实例化
    template void printSnapshotInfo<std::string>(const ItemSnapshotList<std::string>&);
    template void printSnapshotInfo<int>(const ItemSnapshotList<int>&);
    template void printSnapshotInfo<double>(const ItemSnapshotList<double>&);
    
    template void printDiffStats<std::string>(const typename DiffUtil<std::shared_ptr<PagingItem<std::string>>>::DiffResult&);
    template void printDiffStats<int>(const typename DiffUtil<std::shared_ptr<PagingItem<int>>>::DiffResult&);
    template void printDiffStats<double>(const typename DiffUtil<std::shared_ptr<PagingItem<double>>>::DiffResult&);
}

// ============ 错误处理 ============

namespace ErrorHandling {
    
    // 处理diff计算错误
    void handleDiffError(const std::exception& e) {
        LOGE("Diff calculation error: %{public}s", e.what());
    }
    
    // 处理提交数据错误
    void handleSubmitError(const std::exception& e) {
        LOGE("Submit data error: %{public}s", e.what());
    }
    
    // 创建安全的错误回调
    std::function<void(const std::string&)> createSafeErrorCallback(
        std::function<void(const std::string&)> userCallback) {
        
        return [userCallback](const std::string& error) {
            try {
                if (userCallback) {
                    userCallback(error);
                }
            } catch (const std::exception& e) {
                LOGE("Error in user callback: %{public}s", e.what());
            } catch (...) {
                LOGE("Unknown error in user callback");
            }
        };
    }
}

// ============ 工厂函数 ============

// 为常用类型提供默认diff回调实现
template<typename T>
class DefaultDiffCallback : public DiffUtil<std::shared_ptr<PagingItem<T>>>::ItemCallback {
public:
    bool areItemsTheSame(const std::shared_ptr<PagingItem<T>>& oldItem,
                        const std::shared_ptr<PagingItem<T>>& newItem) const override {
        if (!oldItem || !newItem) return false;
        return oldItem->id == newItem->id;
    }
    
    bool areContentsTheSame(const std::shared_ptr<PagingItem<T>>& oldItem,
                           const std::shared_ptr<PagingItem<T>>& newItem) const override {
        if (!oldItem || !newItem) return false;
        return oldItem->data == newItem->data;
    }
    
    void* getChangePayload(const std::shared_ptr<PagingItem<T>>& oldItem,
                          const std::shared_ptr<PagingItem<T>>& newItem) const override {
        return nullptr;
    }
};

// 创建带默认配置的AsyncPagingDataDiffer
template<typename T>
std::unique_ptr<AsyncPagingDataDiffer<T>> createDefaultPagingDiffer(
    ListUpdateCallback* updateCallback) {
    
    LOGI("Creating default paging differ");
    auto diffCallback = std::make_unique<DefaultDiffCallback<T>>();
    return std::make_unique<AsyncPagingDataDiffer<T>>(
        std::move(diffCallback),
        updateCallback ? updateCallback : createDefaultListUpdateCallback().release()
    );
}

// 显式实例化工厂函数
template std::unique_ptr<AsyncPagingDataDiffer<std::string>> 
    createDefaultPagingDiffer<std::string>(ListUpdateCallback*);
template std::unique_ptr<AsyncPagingDataDiffer<int>> 
    createDefaultPagingDiffer<int>(ListUpdateCallback*);
template std::unique_ptr<AsyncPagingDataDiffer<double>> 
    createDefaultPagingDiffer<double>(ListUpdateCallback*);